import React, { useEffect, useState, useRef } from "react";
import {Input, message, Tabs, Menu, Tree} from 'antd';
import { request } from 'dw-mx-request';
import './style/operationPanel.css'
import LeftPanel from '@/application/LeftPanel';
import RightPanel from '@/application/RightPanel';
import {Element} from '@/DragAndDrop/Content';
import {DndProvider} from "react-dnd";
import {HTML5Backend} from "react-dnd-html5-backend";
import {JsonContext} from "@/DragAndDrop/provider";
import savePic from './style/images/save.png';
import {RollbackOutlined,ProjectOutlined,DatabaseOutlined,PictureFilled,AppstoreFilled,MenuOutlined,SettingOutlined,CloseOutlined} from 'dw-mx-icons';
import {useHistory, useLocation} from "dw-mx-router";

const {SubMenu} = Menu;
const defaultJson = {
    "type":{
        "name":'bigscreencanvas'// 六个type，bigscreencanvas（布局），basecharts（常规charts），mapcharts（地图charts），reacteditor（自定义组件）,rowflex(横向布局组件),colflex(纵向布局组件)
    },// 数据类型
    "children":[],
    "id":'mainPage',// 组件id，mainPage为主页面
    "props":{
        "designWidth":'1920px',// 主页的设计稿宽度，即配置的分辨率
        "designHeight":'1080px',// 主页的设计稿高度，即配置的分辨率
        "bgpic":'',
    },// 组件参数
    "addition":{
        "position":{},// 定制化的定位属性,布局用,主页面不需要此属性
        "function":{
            "functionName":{
                name:"test",
                body:"const test = () =>{alert(1);}"
            }
        },
        "layout":"collayout"
    },
    "mappingVariableName":""
};
export default function MainPanel(props) {

    const [currentComponent,setCurrentComponent] = useState();
    const [scaling,setScaling] = useState(100);

    const history = useHistory();
    const location = useLocation();
    const {close,setClose,pageClose,setPageClose,pageJson,setPageJson,appid,pageid} = props;
    const ref = useRef();
    const scalingRef = useRef();
    scalingRef.current = scaling;

    const changeComponentConfig = (changeJson,allJson)=>{
        const result = changeComponent(changeJson,allJson);
        setPageJson(result);
    };

    const changeComponent = (json:{},alljson:{})=>{
        const jsonData = {...alljson};
        if(json['id'] === jsonData['id']){
            return {...json}
        }
        else{
            if(jsonData['children'] && jsonData['children']['length'] > 0){
                const children = jsonData['children'];
                const newChildren = children.map((value)=>{
                    return changeComponent(json,value);
                });
                return {...jsonData,
                    children:newChildren
                }
            }else{
                return jsonData;
            }
        }
    };

    useEffect(()=>{
        setCurrentComponent(pageJson);
        document.getElementById('mainPage').addEventListener('wheel', function(e) {
            if(e.wheelDelta < 0){
                document.getElementById('mainPage').style.zoom = '50%'
            }else{
                document.getElementById('mainPage').style.zoom = '100%'
            }
            e.preventDefault(); // Prevent user scroll during page jump
        }, {
            passive: false
        });
    },[]);


    const savePageJson = async () => {
        await request('/mx/bigScreen/savePageJson', {
            pageid: pageID,
            pagejson: JSON.stringify(pageJson)
        });
        message.success('保存成功');
    };

    const ctrlDown = (e) =>{
        console.log("按键按下：",e.ctrlKey);
        if(e.ctrlKey){
            e.preventDefault();
            ref.current = "on";
        }
    };

    const ctrlUp = (e) =>{
        console.log("按键放开：",e.ctrlKey);
        if(e.ctrlKey){
            ref.current = "off";
        }
    };
    const resolution = (pageJson) =>{
        try{
            const width = pageJson['props']['designWidth'] + '';
            const height = pageJson['props']['designHeight'] + '';
            return width + ' X '+ height;
        }catch(e){
            return null;
        }
    };
    return (
        <div style={{height:'100%'}}>
            {/*<div className={'dlc-mp-save'} onClick={()=>savePageJson()}>*/}
                {/*<img className={'dlc-mp-save-pic'} src={savePic} />*/}
            {/*</div>*/}
            <DndProvider backend={HTML5Backend}>
                <JsonContext.Provider value={{
                    pageJson:pageJson,
                    setPageJson:setPageJson,
                    changeComponentConfig:changeComponentConfig,
                    setCurrentComponent:setCurrentComponent,
                    currentComponent:currentComponent
                }
                }>
                    {/*悬浮部分内容*/}
                    <div>
                        <div style={{display:pageClose ? "none":"",position:"absolute",top:'0.8rem',left:'calc( 25% + 0.8rem )',zIndex:1,backgroundColor:'#fff',border:'1px solid',borderRadius:'8px',padding:'5px'}}>
                            <div style={{position:"relative"}}>
                                <CloseOutlined onClick={()=>{
                                    setPageClose(true);
                                }} style={{color:"red",position:"absolute",right:0}}/>
                            </div>
                            <div style={{height:"100%",display:'inline-block',position:"relative",margin:'10px',top:'10px'}}>
                                <Tree showLine treeData={props.panes}/>
                            </div>
                            <div onClick={()=>{

                            }} style={{marginLeft:'calc( 100% - 0.4rem)',color:'#fff',position:'relative',height:'0.4rem',width:'0.4rem',right:0,bottom:'0',border:'1px solid',zIndex:1,backgroundColor:"#2894FF",borderRadius:'50%'}}>
                                <div style={{position:'relative',display:'block',fontSize:'12px',top:'calc( 50% - 7px )',width:'100%',textAlign:'center'}}>
                                    新增
                                </div>
                            </div>
                        </div>
                        <div style={{display:close ? "none" : "",top:'0.8rem',right:'0.5rem',position:'absolute',border:'1px solid',zIndex:1,backgroundColor:"#fff",height:'auto',borderRadius:'8px',fontSize:'16px',padding:'5px'}}>
                            <div style={{position:"relative"}}>
                                <CloseOutlined onClick={()=>{
                                    setClose(true);
                                }} style={{color:"red",position:"absolute",right:0}}/>
                            </div>
                            <div style={{display:'inline-block',position:"relative",margin:'10px',top:'10px'}}>当前分辨率：{resolution(pageJson)}</div>
                        </div>
                        <div onClick={()=>{

                        }} style={{display:'block',color:'#fff',position:'absolute',height:'0.5rem',width:'0.5rem',right:'50px',bottom:'50px',border:'1px solid',zIndex:1,backgroundColor:"#2894FF",borderRadius:'50%'}}>
                            <div style={{position:'relative',display:'block',fontSize:'14px',top:'calc( 50% - 10px )',width:'100%',textAlign:'center'}}>
                                新增
                            </div>
                        </div>
                    </div>
                    <div className={'dlc-mp-left'}>
                        <LeftPanel appID={appid} pageid={pageid}/>
                    </div>
                    <div className={'dlc-mp-center'}>
                        <div id={'mainPage_outer'} onKeyUp={ctrlUp} onKeyDown={ctrlDown} style={{height:'100%',position:'relative',width:'100%',overflow:'auto',border:'1px solid #000'}}>
                            <Element key={"mainPage"} json={pageJson}/>
                        </div>
                    </div>
                </JsonContext.Provider>
            </DndProvider>
        </div>
    );
}